/**
 * Copyright 2011 HNB. All rights reserved.
 * HNB PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package my.hnb.android.view.karaoke;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import my.hnb.android.common.AppInfo;
import my.hnb.android.constant.Constants;
import my.hnb.android.constant.SharedPref;
import my.hnb.android.dto.OptionItemDTO;
import my.hnb.android.dto.SongTable;
import my.hnb.android.model.SQLUtils;
import my.hnb.android.ultils.AppUltils;
import my.hnb.android.ultils.DateUtil;
import my.hnb.android.ultils.Encryption;
import my.hnb.android.ultils.StringUtil;
import my.hnb.android.ultils.download.DownloadFile;
import my.hnb.android.ultils.download.ExternalStorage;
import my.hnb.android.view.base.BaseActivity;
import my.hnb.android.view.common.Splashscreen;
import my.hnb.songnhac.R;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * settting cap nhat
 * 
 * @author BANGHN
 */
public class SettingView extends BaseActivity implements OnClickListener {
	final int ACTION_UPDATE_OK = 1;
	final int ACTION_UPDATE_LATER = 0;
	LinearLayout llCheckUpdate;
	TextView tvLastUpdate;
	TextView tvCheckUpdate;
	TextView tvAppVersion;
	TextView tvInfo;
	boolean isHaveUpdate = false;
	int lastLogId = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_setting);
		ivMenu.setVisibility(View.GONE);
		this.setTitleText("Thông tin chương trình");
		llCheckUpdate = (LinearLayout) findViewById(R.id.llCheckUpdate);
		tvCheckUpdate = (TextView) findViewById(R.id.tvCheckUpdate);
		tvInfo = (TextView) findViewById(R.id.tvInfo);
		tvLastUpdate = (TextView) findViewById(R.id.tvLastUpdate);
		tvAppVersion = (TextView) findViewById(R.id.tvAppVersion);
		llCheckUpdate.setOnClickListener(this);
		tvCheckUpdate.setOnClickListener(this);
		tvInfo.setOnClickListener(this);

		SharedPreferences sharedPreferences = AppInfo.getInstance().getAppContext()
				.getSharedPreferences(Splashscreen.PREFS_PRIVATE, Context.MODE_PRIVATE);
		lastLogId = sharedPreferences.getInt(SharedPref.SYN_LOG_ID, 0);
		isHaveUpdate = sharedPreferences.getBoolean(SharedPref.SYN_HAVE_UPDATE, false);
		String lastUpdate = sharedPreferences.getString(SharedPref.SYN_LAST_DATE, "");
		tvLastUpdate.setText(StringUtil.getString(R.string.last_update) + " : " + lastUpdate);
		if (isHaveUpdate) {
			tvInfo.setText("(Có cập nhật mới)");
		}

		try {
			String verInfo = null;
			String versionApp = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
			Date date = AppUltils.apkUpdateTime();
			String dateApp = DateUtil.convertDateTimeWithFormat(date, DateUtil.TIME_UPDATE);

			if (!StringUtil.isNullOrEmpty(versionApp)) {
				verInfo = "Phiên bản " + versionApp;
			}
			if (!StringUtil.isNullOrEmpty(dateApp)) {
				verInfo += " cập nhật lúc " + dateApp;
			}
			if (!StringUtil.isNullOrEmpty(verInfo)) {
				tvAppVersion.setText(verInfo);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		if (v == llCheckUpdate || v == tvCheckUpdate || v == tvInfo) {
			if (!AppUltils.checkNetworkAccess()) {
				showMessage("Không có kết nối mạng, vui lòng kiểm tra lại");
			} else {
				if (isHaveUpdate) {
					showDialogConfirmUpdate();
				} else {
					new CheckUpdateSong().execute(Constants.URL_SONG_UPDATE + new Encryption().decrypt(AppInfo.K_LINK, Constants.K_SONG));
				}
				//new UpdateDataAsync().execute("");
			}
		}
	}

	@Override
	public void onEvent(View v, int action, Object userData) {
		switch (action) {
		case ACTION_UPDATE_OK:
			fileUpdate = 1;
			new UpdateDataAsync().execute("");
			break;
		default:
			super.onEvent(v, action, userData);
			break;
		}
	}

	private void showDialogConfirmUpdate() {
		AppUltils.showDialogConfirm(this, StringUtil.getString(R.string.update_notice_title),
				StringUtil.getString(R.string.update_notice_content), StringUtil.getString(R.string.button_agree),
				ACTION_UPDATE_OK, StringUtil.getString(R.string.button_later), ACTION_UPDATE_LATER, null);
	}

	private class CheckUpdateSong extends AsyncTask<String, Void, Exception> {
		@Override
		protected void onPreExecute() {
			showProgressDialog("Đang kiểm tra cập nhật dữ liệu mới...");
		}

		@Override
		protected Exception doInBackground(String... params) {
			String url = (String) params[0];
			try {
				downloadSongUpdateInfo(url);
			} catch (Exception e) {
				e.printStackTrace();
				return e;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Exception result) {
			if (AppInfo.getInstance().isHaveUpdate) {
				showDialogConfirmUpdate();
			}else{
				closeProgressDialog();
				tvInfo.setVisibility(View.INVISIBLE);
				Toast.makeText(AppInfo.getInstance().getAppContext(), "Không có cập nhật mới!", Toast.LENGTH_LONG)
						.show();
			}
		}
	}

	private void downloadSongUpdateInfo(String url) {
		File fileDir = ExternalStorage.getAdPath();
		// File path to store .zip file before unzipping
		File file = new File(fileDir.getPath() + "/songUpdate.txt");
		// File outputDir = ExternalStorage.getAdPath();

		try {
			DownloadFile.downloadWithURLConnection(url, file, fileDir);
			readFileUpdate(file);
		} finally {
			file.delete();
		}
	}

	private static void readFileUpdate(File file) {
		InputStream fis;
		BufferedReader br;
		String line;
		try {
			fis = new FileInputStream(file);
			br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
			SharedPreferences sharedPreferences = AppInfo.getInstance().getAppContext()
					.getSharedPreferences(Splashscreen.PREFS_PRIVATE, Context.MODE_PRIVATE);
			int logId = sharedPreferences.getInt(SharedPref.SYN_LOG_ID, 0);

			ArrayList<OptionItemDTO> arrayLink = new ArrayList<OptionItemDTO>();
			while ((line = br.readLine()) != null) {
				line = line.trim();
				String[] array = line.split(",");
				if (logId < Integer.parseInt(array[0])) {
					OptionItemDTO item = new OptionItemDTO();
					item.strText = array[1];
					item.value = Integer.parseInt(array[0]);
					arrayLink.add(0, item);
				}
			}

			if (arrayLink.size() > 0) {
				AppInfo.getInstance().isHaveUpdate = true;
				AppInfo.getInstance().setListLinkUpdate(arrayLink);
				Editor prefsPrivateEditor = sharedPreferences.edit();
				prefsPrivateEditor.putBoolean(SharedPref.SYN_HAVE_UPDATE, true);
				prefsPrivateEditor.commit();
			} else {
				AppInfo.getInstance().isHaveUpdate = false;
			}

		} catch (Exception e) {
			System.out.print("Exception : " + e.getMessage());
			e.printStackTrace();
		} finally {
			br = null;
			fis = null;
		}
	}

	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	private ProgressDialog mProgressDialog;

	int fileUpdate = 1;
	Handler dialogHandler = new Handler();
	Runnable showDialogRunnable = new Runnable() {
		public void run() {
			if (AppInfo.getInstance().getLinkUpdate().size() > 1) {
				closeProgressDialog();
				showProgressDialog("Cập nhật bài hát mới, vui lòng chờ... (Phần " + fileUpdate + "/"
						+ AppInfo.getInstance().getLinkUpdate().size() + ")");
				mProgressDialog.setMessage("Cập nhật bài hát (Phần " + fileUpdate + "/"
						+ AppInfo.getInstance().getLinkUpdate().size() + ")...");
			} else {
				showProgressDialog("Cập nhật bài hát mới, vui lòng chờ...");
			}
		}
	};
	Runnable closeDialogRunnable = new Runnable() {
		public void run() {
			closeProgressDialog();
		}
	};

	class UpdateDataAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_DOWNLOAD_PROGRESS);

			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... arg0) {
			try {
				//int fileFize = 1;
				int fileFize = AppInfo.getInstance().getLinkUpdate().size();
				for (int i = 0; i < fileFize; i++) {
					runOnUiThread(showDialogRunnable);

					File download = downloadAndUnzip(AppInfo.getInstance().getLinkUpdate().get(i).strText);
					FileInputStream in = new FileInputStream(download);
					//AssetManager assetManager = AppInfo.getInstance().getAppContext().getAssets();
					//InputStream in = assetManager.open("Karaoke_song_p8.xls");
					
					// Create a POIFSFileSystem object
					POIFSFileSystem myFileSystem = new POIFSFileSystem(in);

					// Create a workbook using the File System
					HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

					// Get the first sheet from workbook
					HSSFSheet mySheet = myWorkBook.getSheetAt(0);
					Iterator<?> rowIter = mySheet.rowIterator();
					int totalRow = mySheet.getPhysicalNumberOfRows();
					mProgressDialog.setMax(totalRow);
					runOnUiThread(closeDialogRunnable);

					int index = 0;
					//ArrayList<String> columns = new ArrayList<String>();
					ArrayList<String> values;
					while (rowIter.hasNext()) {
						HSSFRow myRow = (HSSFRow) rowIter.next();
						//Iterator<?> cellIter = myRow.cellIterator();
						values = new ArrayList<String>();
						for(int j = 0; j <= 7; j++){
							HSSFCell myCell = myRow.getCell(j);
							if(myCell != null){
								values.add(myCell.toString());
							}else{
								values.add("");
							}
						}
						if (index != 0 && StringUtil.checkIfNumber(values.get(0).replace(".0", ""))
								&& Integer.parseInt(values.get(0).replace(".0", "")) > 0) {
							ContentValues content = initDataRow(values);
							String[] params = { values.get(0).replace(".0", "") };
							if (SQLUtils.getInstance().isExistSong(values.get(0).replace(".0", ""))) {
								// update
								SQLUtils.getInstance().getmDB().update("SONG", content, "SONG_CODE = ?", params);
							} else {
								// insert
								SQLUtils.getInstance().getmDB().insert("SONG", null, content);
							}
						}
						index++;
						publishProgress("" + index);
					}
					updateSynLastLogId(AppInfo.getInstance().getLinkUpdate().get(i).value);
					fileUpdate++;
					//download = null;
					//fi = null;
				}
				AppInfo.getInstance().resetListLinkUpdate();
				isHaveUpdate = false;
			} catch (Throwable e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onProgressUpdate(String... progress) {
			mProgressDialog.setProgress(Integer.parseInt(progress[0]));
		}

		@Override
		protected void onPostExecute(String unused) {
			dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
			closeProgressDialog();
			updateSynInfo();
		}
	}

	private File downloadAndUnzip(String url) {
		File fileUpdate;
		File zipDir = ExternalStorage.getPathSynData();
		// File path to store .zip file before unzipping
		File zipFile = new File(zipDir.getPath() + "/temp.zip");
		File outputDir = ExternalStorage.getPathSynData();

		try {
			DownloadFile.downloadWithURLConnection(url, zipFile, zipDir);
			String fileName = DownloadFile.unzipReturnName(getApplicationContext(), zipFile, outputDir);
			fileUpdate = new File(zipDir.getPath() + "/" + fileName);
		} finally {
			zipFile.delete();
		}
		return fileUpdate;
	}

	private ContentValues initDataRow(ArrayList<String> values) {
		ContentValues editedValues = new ContentValues();
		try {
			editedValues.put(SongTable.COLUMN_SONG_CODE, values.get(0).replace(".0", ""));
			editedValues.put(SongTable.COLUMN_SONG_NAME, values.get(1));
			editedValues.put(SongTable.COLUMN_MUSICAN, values.get(2));
			editedValues.put(SongTable.COLUMN_SINGER, values.get(3));
			editedValues.put(SongTable.COLUMN_VOL, values.get(4).replace(".0", ""));
			editedValues.put(SongTable.COLUMN_TYPE, values.get(5).replace(".0", ""));
			editedValues.put(SongTable.COLUMN_LYRIC_SHORT, values.get(6));
			editedValues.put(SongTable.COLUMN_LYRIC_FULL, new Encryption().encrypt(AppInfo.K_LYRIC, values.get(7)));

			String nameEngUpperCase = StringUtil.getEngStringFromUnicodeString(values.get(1)).toUpperCase();
			editedValues.put(SongTable.COLUMN_SONG_NAME_SEARCH, nameEngUpperCase);
			editedValues.put(SongTable.COLUMN_MUSICAN_SEARCH, StringUtil.getEngStringFromUnicodeString(values.get(2))
					.toUpperCase());
			editedValues.put(SongTable.COLUMN_LYRIC_SEARCH, StringUtil.getEngStringFromUnicodeString(values.get(6))
					.toUpperCase());
			editedValues.put(SongTable.COLUMN_SONG_NAME_SHORT, StringUtil.getFristCharacterOfLine(nameEngUpperCase));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return editedValues;
	}

	private void updateSynInfo() {
		SharedPreferences sharedPreferences = AppInfo.getInstance().getAppContext()
				.getSharedPreferences(Splashscreen.PREFS_PRIVATE, Context.MODE_PRIVATE);
		Editor prefsPrivateEditor = sharedPreferences.edit();
		prefsPrivateEditor.putString(SharedPref.SYN_LAST_DATE, DateUtil.now(DateUtil.TIME_UPDATE));
		tvLastUpdate.setText(StringUtil.getString(R.string.last_update) + " : " + DateUtil.now(DateUtil.TIME_UPDATE));
		boolean isHavaUpdate = false;
		if (AppInfo.getInstance().getLinkUpdate().size() > 0)
			isHavaUpdate = true;
		if (isHaveUpdate) {
			tvInfo.setText("(Có cập nhật mới)");
			tvInfo.setVisibility(View.VISIBLE);
		}else{
			tvInfo.setVisibility(View.INVISIBLE);
		}
		prefsPrivateEditor.putBoolean(SharedPref.SYN_HAVE_UPDATE, isHavaUpdate);
		prefsPrivateEditor.commit();
	}

	private void updateSynLastLogId(int logId) {
		SharedPreferences sharedPreferences = AppInfo.getInstance().getAppContext()
				.getSharedPreferences(Splashscreen.PREFS_PRIVATE, Context.MODE_PRIVATE);
		int lastLogId = sharedPreferences.getInt(SharedPref.SYN_LOG_ID, 0);
		if (logId > lastLogId) {
			Editor prefsPrivateEditor = sharedPreferences.edit();
			prefsPrivateEditor.putInt(SharedPref.SYN_LOG_ID, logId);
			prefsPrivateEditor.commit();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMax(0);
			mProgressDialog.setMessage("Cập nhật bài hát..");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}
}
